package janino.resource;

import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

/**
 * Stores a stream of bytes in a named resource.
 */
public abstract class FileResourceCreator implements ResourceCreator {

    public final OutputStream createResource(String resourceName) throws IOException {
        FileConnection file = this.getFile(resourceName);
       
        // Create directory for class file if it does not exist.
        FileConnection dir = (FileConnection) Connector.open(getParent(file.getURL()));

        if (dir != null && (!dir.exists() || !dir.isDirectory())) {
            dir.mkdir();
            // throw new IOException("Cannot create directory for class file \"" + file + "\"")
        }

        if(!file.exists()){
            file.create();
        }
        
        // Create the file.
        return file.openDataOutputStream();
    }

    public final void deleteResource(String resourceName) {
        try {
            this.getFile(resourceName).delete();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static String getParent(String url) {
      
        int index = url.lastIndexOf('/', url.length() - 2);
      
        String parent = url.substring(0, index + 1);
        
        return parent;
    }

    protected abstract FileConnection getFile(String resourceName);
}
